package cn.mhome.merchant.framework.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.UUID;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import cn.mhome.merchant.entity.business.param.BusinessParam;
import cn.mhome.merchant.entity.business.result.BusinessResult;
import cn.mhome.merchant.entity.common.result.CommonResult;
import cn.mhome.merchant.entity.common.result.DataResult;
import cn.mhome.merchant.entity.common.result.Pager;
import cn.mhome.merchant.framework.data.ImageUploadData;
import cn.mhome.merchant.server.business.service.BusinessService;
import cn.mhome.merchant.util.Base64;
import cn.mhome.merchant.util.StringUtils;

/**
 * 系统用户管理
 * @author lvpeng
 */
@Controller
@RequestMapping("/api/business")
public class BusinessController {
	
	@Resource
	private BusinessService businessService;
	
	/**
	 * 查询商户列表
	 * @param sysUserParam
	 * @return
	 */
	@RequestMapping(value = "/findForPage", method = { RequestMethod.POST,
			RequestMethod.GET }, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public DataResult findForPage(@RequestBody BusinessParam businessParam){
		DataResult dataResult = new DataResult();
		try {
			Pager<BusinessResult> data = businessService.findForPage(businessParam);
			if(data != null && data.getData() != null){
				for(BusinessResult bt : data.getData()){
					if(!StringUtils.isBlank(bt.getBusinessImage())){
						File file = new File(bt.getBusinessImage());
						if(file != null && file.exists()){
							bt.setBusinessImageByte(Base64.encodeFromFile(file.getPath()));
						}
					}
					if(!StringUtils.isBlank(businessParam.getVisitFrom()) &&
							 businessParam.getVisitFrom().equals("weixin")){
						if(!StringUtils.isBlank(bt.getOutletDetail())){
							String detail = bt.getOutletDetail().trim().replace("\r\n", "\n").replace(" ","");
							String[] details = detail.split("\n");
							StringBuffer sb = new StringBuffer();
							for(String detailStr : details){
								sb.append("<p>").append(detailStr).append("</p>");
							}
							bt.setOutletDetail(sb.toString());
						}
					}
				}
			}
			dataResult.setData(data);
		} catch (Exception e) {
			dataResult.setCode(500);
			dataResult.setMsg("查询商户列表异常");
		}
		return dataResult;
	}
	
	/**
	 * 查询商户列表
	 * @param sysUserParam
	 * @return
	 */
	@RequestMapping(value = "/visit", method = { RequestMethod.POST,
			RequestMethod.GET }, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public DataResult visit(@RequestParam(value = "businessId", required = true) long businessId ,
			@RequestParam(value = "visitType", required = true) int visitType ,
			@RequestParam(value = "openId", required = false) String openId){
		DataResult dataResult = new DataResult();
		try {
			BusinessParam businessParam = new BusinessParam();
			businessParam.setBusinessId(businessId);
			businessParam.setVisitType(visitType);
			businessParam.setOpenId(openId);
			CommonResult data = businessService.visit(businessParam);
			dataResult.setData(data);
		} catch (Exception e) {
			dataResult.setCode(500);
			dataResult.setMsg("保存异常");
		}
		return dataResult;
	}
	
	/**
	 * 查询商户列表
	 * @param sysUserParam
	 * @return
	 */
	@RequestMapping(value = "/save", method = { RequestMethod.POST,
			RequestMethod.GET }, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public DataResult save(@RequestBody BusinessParam businessParam){
		DataResult dataResult = new DataResult();
		try {
			CommonResult data = businessService.save(businessParam);
			dataResult.setData(data);
		} catch (Exception e) {
			dataResult.setCode(500);
			dataResult.setMsg("保存异常");
		}
		return dataResult;
	}
	
	/**
	 * 删除商户
	 * @param sysUserParam
	 * @return
	 */
	@RequestMapping(value = "/deleteById", method = { RequestMethod.POST,
			RequestMethod.GET }, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public DataResult deleteById(HttpServletRequest request,@RequestBody BusinessParam businessParam){
		DataResult dataResult = new DataResult();
		try {
			CommonResult data = businessService.delete(businessParam);
			if(data.getCode() == 200){
				String absPath = new File(request.getSession().getServletContext().getRealPath("/")).getParent()+ "/upload/images/";
				String fileName1 =  absPath + businessParam.getBusinessId() +"_1.png";  
				String fileName2 =  absPath + businessParam.getBusinessId() +"_2.png";  
				String fileName3 =  absPath + businessParam.getBusinessId() +"_3.png";  
				String fileName4 =  absPath + businessParam.getBusinessId() +"_4.png";  
				String fileName5 =  absPath + businessParam.getBusinessId() +"_5.png";  
		        File targetFile = new File(fileName1);
		        if(targetFile.exists()){targetFile.delete();}
		        targetFile = new File(fileName2);
		        if(targetFile.exists()){targetFile.delete();}
		        targetFile = new File(fileName3);
		        if(targetFile.exists()){targetFile.delete();}
		        targetFile = new File(fileName4);
		        if(targetFile.exists()){targetFile.delete();}
		        targetFile = new File(fileName5);
		        if(targetFile.exists()){targetFile.delete();}
			}
			dataResult.setData(data);
		} catch (Exception e) {
			dataResult.setCode(500);
			dataResult.setMsg("保存异常");
		}
		return dataResult;
	}
	
	private static final String IMAGE_PATH = "/merchant/images/";
	/**
     * 保存项目图片
     * @return
     */
    @RequestMapping(value = "/upload")
    @ResponseBody
    public DataResult upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model){
        DataResult dataResult = new DataResult();
        try{
			BufferedImage bufferedImage = ImageIO.read(file.getInputStream()); 
			if(bufferedImage == null){
				dataResult.setCode(300);
				dataResult.setMsg("解析失败,只能上传图片");
				return dataResult;
			}
			
			String contentType = file.getContentType();
			if("image/jpg,image/jpeg,image/png".indexOf(contentType) == -1){
				dataResult.setCode(300);
				dataResult.setMsg("图片格式只支持png、jpg或者jpeg");
				return dataResult;
			}
	        int width = bufferedImage.getWidth();   
	        int height = bufferedImage.getHeight(); 
	        if(width != 150 || height != 190){
	        	dataResult.setCode(300);
				dataResult.setMsg("图片尺寸必须为150*190像素");
				return dataResult;
	        }
	        
        	String orgFileName = file.getOriginalFilename();
	        String fileName =  UUID.randomUUID().toString() + orgFileName.substring(orgFileName.lastIndexOf("."),orgFileName.length());  
	        File targetFile = new File(IMAGE_PATH + fileName);
	        if(targetFile.exists()){
	        	targetFile.delete();
	        }
	        file.transferTo(targetFile);
			String image = Base64.encodeFromFile(targetFile.getAbsolutePath());
			dataResult.setCode(200);
			dataResult.setMsg("上传成功");
			
			ImageUploadData data = new ImageUploadData();
			data.setImage(image);
			data.setHeight(height);
			data.setWidth(width);
			data.setFilePath(IMAGE_PATH + fileName); //文件路径
			dataResult.setData(data);
			
        }catch(Exception e){
            dataResult.setCode(500);
            dataResult.setMsg("项目图片失败");
        }
        return dataResult;
    }
    
    
    /**
     * 保存项目图片
     * @return
     */
    @RequestMapping(value = "/uploadImages")
    @ResponseBody
    public DataResult uploadImages(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model){
        DataResult dataResult = new DataResult();
        try{
        	String businessId = request.getParameter("businessId");
        	String index = request.getParameter("index");
        	String absPath = new File(request.getSession().getServletContext().getRealPath("/")).getParent()+ "/upload/images/";
			BufferedImage bufferedImage = ImageIO.read(file.getInputStream()); 
			if(bufferedImage == null){
				dataResult.setCode(300);
				dataResult.setMsg("解析失败,只能上传图片");
				return dataResult;
			}
	        String fileName =  businessId +"_"+index+ ".png";
	        File targetFile = new File(absPath + fileName);
	        if(targetFile.exists()){
	        	targetFile.delete();
	        }
	        file.transferTo(targetFile);
			String image = Base64.encodeFromFile(targetFile.getAbsolutePath());
			dataResult.setCode(200);
			dataResult.setMsg("上传成功");
			
			ImageUploadData data = new ImageUploadData();
			data.setImage(image);
			data.setFilePath(fileName); //文件路径
			dataResult.setData(data);
			
        }catch(Exception e){
            dataResult.setCode(500);
            dataResult.setMsg("项目图片失败");
        }
        return dataResult;
    }
}
